package edu.zut.cs.javaee.manager.course;

import edu.zut.cs.javaee.manager.base.exception.GlobalException;
import edu.zut.cs.javaee.manager.base.util.Page;
import edu.zut.cs.javaee.manager.base.util.PageList;
import edu.zut.cs.javaee.manager.course.dao.CourseDao;
import edu.zut.cs.javaee.manager.course.domain.Course;
import edu.zut.cs.javaee.manager.studentcourse.dao.StudentCourseDao;
import edu.zut.cs.javaee.manager.studentcourse.domain.StudentCourse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * 课程service
 */
@Service
@Transactional
public class CourseService {

    @Autowired
    private CourseDao courseDao;
    @Autowired
    private StudentCourseDao studentCourseDao;

    public PageList<Course> getCourseList(Page page, String name, Integer userId, Integer role) {
        String hql = " from Course where delFlag = 0 ";

        if (role == 2) {
            hql += " and teacher.id = " + userId;
        }

        if (!ObjectUtils.isEmpty(name)) {
            hql += " and name like '%" + name + "%'";
        }
        return courseDao.findPageListByHql(page,hql);

    }
    

    public void add(Course course) {
        courseDao.save(course);
    }

    public void update(Course c) {
        Course course = courseDao.get(c.getId());
        String courseNo = course.getCourseNo();
        BeanUtils.copyProperties(c,course);
        course.setCourseNo(courseNo);
        courseDao.update(course);
    }


    public void delete(Course c) {
        Course course = courseDao.get(c.getId());
        course.setDelFlag(1);
    }

    public void xuanKe(StudentCourse sc) throws Exception {
        List<StudentCourse> list = studentCourseDao.findList(" from StudentCourse where course.id = ?0 and student.id = ?1", sc.getCourse().getId(), sc.getStudent().getId());
        if (!ObjectUtils.isEmpty(list)) {
            throw new GlobalException("请勿重复选择同一门课程");
        }
        studentCourseDao.save(sc);
    }
}
